﻿using DocumentFormat.OpenXml.Drawing.Charts;
using Microsoft.Extensions.Configuration;
using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.Entities.NIP_Wechat;
using NP.Enterprise.Utils.Http;
using OfficeOpenXml.FormulaParsing.Excel.Functions.DateTime;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace NP.BPMReportPlatform.RecurringJobs
{
    public class ToDoAppServiceJob : BpmReportPlatformRecurringJob, IToDoAppServiceJob
    {
        private readonly INPRestHttpHelper _httpClient;
        private readonly string _syncFanWeiToDoUrl, _syncBPMToDoUrl, _syncBPMNEWToDoUrl,
            _syncWebOAToDoUrl, _syncRiskHTToDoUrl, _syncRiskXYToDoUrl, _syncCloudPenseToDoUrl, _syncZBZCToDoUrl;

        private readonly SqlSugarClient _dbWechat, _dbWechatHistory;

        public ToDoAppServiceJob(INPRestHttpHelper httpClient, IConfiguration configuration, ISqlSugarAppService sqlSugarAppService)
        {
            _httpClient = httpClient;
            _syncFanWeiToDoUrl = configuration["BPMToDo:SyncFanWeiToDoUrl"];
            _syncBPMToDoUrl = configuration["BPMToDo:SyncBPMToDoUrl"];

            _syncBPMNEWToDoUrl = configuration["BPMToDo:SyncBPMNEWToDoUrl"];
            _syncWebOAToDoUrl = configuration["BPMToDo:SyncWebOAToDoUrl"];
            _syncRiskHTToDoUrl = configuration["BPMToDo:SyncRiskHTToDoUrl"];
            _syncRiskXYToDoUrl = configuration["BPMToDo:SyncRiskXYToDoUrl"];
            _syncCloudPenseToDoUrl = configuration["BPMToDo:SyncCloudPenseToDoUrl"];
            _syncZBZCToDoUrl = configuration["BPMToDo:SyncZBZCToDoUrl"];

            _dbWechat = sqlSugarAppService.GetNIP_WechatInstance();
            _dbWechatHistory = sqlSugarAppService.GetNIP_Wechat_HistoryInstance();

        }

        /// <summary>
        /// 同步泛微近6个月的待办
        /// </summary>
        /// <returns></returns>
        public async Task SyncFanWeiToDo()
        {
            await _httpClient.PostAsync(_syncFanWeiToDoUrl, "");
        }

        /// <summary>
        /// 同步BPM近6个月的待办
        /// </summary>
        /// <returns></returns>
        public async Task SyncBPMToDo()
        {
            await _httpClient.PostAsync(_syncBPMToDoUrl, "");
        }

        /// <summary>
        /// 同步新BPMNEW近6个月的待办
        /// </summary>
        /// <returns></returns>
        public async Task SyncBPMNEWToDo()
        {
            await _httpClient.PostAsync(_syncBPMNEWToDoUrl, "");
        }

        /// <summary>
        /// 同步WebOA近6个月的待办
        /// </summary>
        /// <returns></returns>
        public async Task SyncWebOAToDo()
        {
            await _httpClient.PostAsync(_syncWebOAToDoUrl, "");
        }

        /// <summary>
        /// 同步RiskHT近6个月的待办
        /// </summary>
        /// <returns></returns>
        public async Task SyncRiskHTToDo()
        {
            await _httpClient.PostAsync(_syncRiskHTToDoUrl, "");
        }

        /// <summary>
        /// 同步RiskXY近6个月的待办
        /// </summary>
        /// <returns></returns>
        public async Task SyncRiskXYToDo()
        {
            await _httpClient.PostAsync(_syncRiskXYToDoUrl, "");
        }

        /// <summary>
        /// 同步移动报销近6个月的待办
        /// </summary>
        /// <returns></returns>
        public async Task SyncCloudPenseToDo()
        {
            await _httpClient.PostAsync(_syncCloudPenseToDoUrl, "");
        }

        /// <summary>
        /// 同步资本资出近6个月的待办
        /// </summary>
        /// <returns></returns>
        public async Task SyncZBZCToDo()
        {
            await _httpClient.PostAsync(_syncZBZCToDoUrl, "");
        }

        /// <summary>
        /// 同步3个月前的已办数据到历史库
        /// </summary>
        /// <returns></returns>
        public async Task SyncWechatToWechatHistory()
        {
            var migrationDate = DateTime.Now.AddMonths(-3);
            for (int i = 1; i <= 240; i++)
            {
                var startDate = migrationDate.AddDays(-(i * 3));
                var endDate = startDate.AddDays(3);

                var jobFlowInstIdList = await _dbWechat.Queryable<WechatJobList>().Where(x => x.ARRIVALDATE >= startDate && x.ARRIVALDATE <= endDate && x.STATUS == 4).Select(x => x.FlowInstID).Distinct().ToListAsync();
                if (i == 240)
                {
                    jobFlowInstIdList = await _dbWechat.Queryable<WechatJobList>().Where(x => x.ARRIVALDATE <= endDate && x.STATUS == 4).Select(x => x.FlowInstID).Distinct().ToListAsync();
                }
                if (jobFlowInstIdList.Count == 0)
                {
                    continue;
                }
                var jobList = await _dbWechat.Queryable<WechatJobList>().Where(x => SqlFunc.ContainsArray(jobFlowInstIdList, x.FlowInstID)).ToListAsync();

                var ignoreFlowInstIDList = jobList.Where(x => x.STATUS == 0).Select(x => x.FlowInstID).Distinct().ToList();

                var migrationJobList = jobList.Where(x => !ignoreFlowInstIDList.Any(y => y == x.FlowInstID)).ToList();
                var migrationFlowInstList = await _dbWechat.Queryable<WechatFlowInst>().Where(x => SqlFunc.ContainsArray(migrationJobList.Select(y => y.FlowInstID).Distinct().ToList(), x.ID)).ToListAsync();

                try
                {
                    _dbWechatHistory.Ado.BeginTran();
                    await _dbWechatHistory.Insertable(migrationFlowInstList).ExecuteCommandAsync();
                    await _dbWechatHistory.Insertable(migrationJobList).ExecuteCommandAsync();
                    _dbWechatHistory.Ado.CommitTran();
                }
                catch (Exception ex)
                {
                    _dbWechatHistory.Ado.RollbackTran();

                    throw new Exception($"数据插入历史库失败，失败原因：{ex.Message}");
                }

                try
                {
                    _dbWechat.Ado.BeginTran();
                    await _dbWechat.Deleteable(migrationFlowInstList).ExecuteCommandAsync();
                    await _dbWechat.Deleteable(migrationJobList).ExecuteCommandAsync();
                    _dbWechat.Ado.CommitTran();
                }
                catch (Exception ex)
                {
                    _dbWechat.Ado.RollbackTran();
                    throw new Exception($"数据删除失败，失败原因：{ex.Message}");
                }

            }

        }

        ///// <summary>
        ///// 同步6个月前的已办数据到历史库
        ///// </summary>
        ///// <returns></returns>
        //public async Task SyncWechatToWechatHistory()
        //{
        //    var migrationDate = DateTime.Now.AddMonths(-6);
        //    for (int i = 1; i <= 240; i++)
        //    {
        //        var startDate = migrationDate.AddDays(-(i * 3));
        //        var endDate = startDate.AddDays(3);
        //        var jobList = new List<WechatJobList>();

        //        jobList = await _dbWechat.Queryable<WechatJobList>().Where(x => x.ARRIVALDATE >= startDate && x.ARRIVALDATE <= endDate).ToListAsync();

        //        var ignoreFlowInstIdList = jobList.Where(x => x.STATUS == 0).Select(x => x.FlowInstID).Distinct().ToList();

        //        var flowInstIdList = jobList.Where(x => !ignoreFlowInstIdList.Any(y => y == x.FlowInstID)).Select(x => x.FlowInstID).Distinct().ToList();
        //        if (flowInstIdList.Count == 0)
        //        {
        //            continue;
        //        }
        //        var migrationFlowInstList = await _dbWechat.Queryable<WechatFlowInst>().Where(x => SqlFunc.ContainsArray(flowInstIdList, x.ID)).ToListAsync();
        //        var migrationJobList = jobList.Where(x => flowInstIdList.Any(y => y == x.FlowInstID)).ToList();

        //        try
        //        {
        //            _dbWechatHistory.Ado.BeginTran();
        //            await _dbWechatHistory.Insertable(migrationFlowInstList).ExecuteCommandAsync();
        //            await _dbWechatHistory.Insertable(migrationJobList).ExecuteCommandAsync();
        //            _dbWechatHistory.Ado.CommitTran();
        //        }
        //        catch (Exception ex)
        //        {
        //            _dbWechatHistory.Ado.RollbackTran();

        //            throw new Exception($"数据插入历史库失败，失败原因：{ex.Message}");
        //        }

        //        try
        //        {
        //            _dbWechat.Ado.BeginTran();
        //            await _dbWechat.Deleteable(migrationFlowInstList).ExecuteCommandAsync();
        //            await _dbWechat.Deleteable(migrationJobList).ExecuteCommandAsync();
        //            _dbWechat.Ado.CommitTran();
        //        }
        //        catch (Exception ex)
        //        {
        //            _dbWechat.Ado.RollbackTran();
        //            throw new Exception($"数据删除失败，失败原因：{ex.Message}");
        //        }

        //    }

        //}

        ///// <summary>
        ///// 同步6个月前的已办数据到历史库
        ///// </summary>
        ///// <returns></returns>
        //public async Task SyncWechatToWechatHistory()
        //{
        //    var migrationDate = DateTime.Now.AddMonths(-6);
        //    for (int i = 1; i <= 12; i++)
        //    {
        //        var date = migrationDate.AddMonths(-i);
        //        var jobList = new List<WechatJobList>();
        //        if (i == 12)
        //        {
        //            jobList = await _dbWechat.Queryable<WechatJobList>().Where(x => x.ARRIVALDATE < migrationDate).ToListAsync();
        //        }
        //        else
        //        {
        //            jobList = await _dbWechat.Queryable<WechatJobList>().Where(x => x.ARRIVALDATE > date && x.ARRIVALDATE < migrationDate).ToListAsync();
        //        }
        //        var ignoreFlowInstIdList = jobList.Where(x => x.STATUS == 0).Select(x => x.FlowInstID).Distinct().ToList();

        //        var flowInstIdList = jobList.Where(x => !ignoreFlowInstIdList.Any(y => y == x.FlowInstID)).Select(x => x.FlowInstID).Distinct().ToList();
        //        var migrationFlowInstList = await _dbWechat.Queryable<WechatFlowInst>().Where(x => SqlFunc.ContainsArray(flowInstIdList, x.ID)).ToListAsync();
        //        var migrationJobList = jobList.Where(x => flowInstIdList.Any(y => y == x.FlowInstID)).ToList();

        //        try
        //        {
        //            _dbWechatHistory.Ado.BeginTran();
        //            await _dbWechatHistory.Insertable(migrationFlowInstList).ExecuteCommandAsync();
        //            await _dbWechatHistory.Insertable(migrationJobList).ExecuteCommandAsync();
        //            _dbWechatHistory.Ado.CommitTran();
        //        }
        //        catch (Exception ex)
        //        {
        //            _dbWechatHistory.Ado.RollbackTran();

        //            throw new Exception($"数据插入历史库失败，失败原因：{ex.Message}");
        //        }

        //        try
        //        {
        //            _dbWechat.Ado.BeginTran();
        //            await _dbWechat.Deleteable(migrationFlowInstList).ExecuteCommandAsync();
        //            await _dbWechat.Deleteable(migrationJobList).ExecuteCommandAsync();
        //            _dbWechat.Ado.CommitTran();
        //        }
        //        catch (Exception ex)
        //        {
        //            _dbWechat.Ado.RollbackTran();
        //            throw new Exception($"数据删除失败，失败原因：{ex.Message}");
        //        }

        //    }

        //}
    }
}
